#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@author: yinzhuoqun
@site: http://zhuoqun.info/
@email: yin@zhuoqun.info
@time: 2025/4/18 16:41
"""

import time
from redis_server import RedisServer
from config import redis_server, redis_password

redis_server = RedisServer(host=redis_server, password=redis_password, db=11)


def save_trace_board_data(nickname=None, mac_serial=None, count=None):
    """
    保存 用户上传上来的键盘使用统计的 数据
    :return:
    """
    today = time.strftime("%Y%m%d")
    key_count = f"trace_board:count:{today}"
    key_nickname = f"trace_board:nickname"
    key_saying_today = f"trace_board:saying:{today}"
    key_saying_all = f"trace_board:saying:all"
    with redis_server.get_connection() as rs11:
        if mac_serial and len(mac_serial) == 29 and count.isdigit():
            rs11.hset(key_count, mac_serial, count)
            key_count_ttl = rs11.ttl(key_count)
            if key_count_ttl == -1:
                rs11.expire(key_count, 86400 * 30)
        if nickname and len(nickname) <= 20 and mac_serial and len(mac_serial) == 29:
            rs11.hset(key_nickname, mac_serial, nickname)

        count_data = rs11.hgetall(key_count)
        nickname_data = rs11.hgetall(key_nickname)
        data = []
        for key, value in count_data.items():
            data.append({"nickname": nickname_data.get(key, "佚名"), "todayCount": int(value), "macSerial": key})

        data.sort(key=lambda x: x['todayCount'], reverse=True)
        my_percent = 0.9999
        saying = rs11.get(key_saying_today)
        if not saying:
            # "没有不能换的键盘，只有累死的牛马"
            saying = rs11.srandmember(key_saying_all)
            if not saying:
                saying = "没有不能换的键盘，只有累死的牛马"
            rs11.set(key_saying_today, saying, 300)
    return {"code": 200, "msg": "查询成功", "data": data, "myPercent": f"{my_percent:.2%}", "saying": saying}, 200
